package com.knight.mall.admin.controller.login;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.knight.mall.admin.exception.WebException;
import com.knight.mall.admin.page.model.EnterpriseAgent;
import com.knight.mall.admin.web.utils.MallApiResponse;
import com.knight.mall.admin.web.utils.MallrApiResponseCode;
import com.knight.mall.dto.EnterpriseDto;
import com.knight.mall.enums.AdminServiceResultCode;
import com.knight.mall.exception.ServiceException;
import com.knight.mall.model.Enterprise;
import com.knight.mall.service.EnterpriseService;

/**
 * 后台用户登录
 * 
 */
@Controller
public class AdminLoginController {
	private static final Logger logger = LoggerFactory.getLogger(AdminLoginController.class);
	@Autowired
	private EnterpriseService enterpriseService;

	/**
	 * 进入登录页面，通过缓存和cookie保存验证码key
	 *
	 * @see
	 */
	@RequestMapping(value = { "", "login" }, method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
		Integer logerrNum = (Integer) request.getSession().getAttribute("logerrNum");
		model.addAttribute("logerrNum", logerrNum);
		return "admin-login";
	}

	/**
	 * 检查是否有恶意的刷屏，如果同一IP不带验证码请求超过3次，则抛出异常
	 *
	 * @see
	 */
	private void checkCaptcha(EnterpriseDto loginDto, HttpServletRequest request) throws WebException {

		Integer loginCount = (Integer) request.getSession().getAttribute("logerrNum");

		String validateCode = loginDto.getValidateCode();
		if (StringUtils.isBlank(validateCode) && loginCount != null && loginCount > 3) {
			throw new WebException(AdminServiceResultCode._2060505.getCode(),
					(AdminServiceResultCode._2060505.getMsg()));
		}
	}

	/**
	 * 用户登录
	 *
	 * @author <a href=mailto:zhangxufeng@ancun.com>ZhangXufeng</a> create at
	 *         2016/4/6 16:25
	 * @version %I%,%G%
	 * @see
	 */
	@RequestMapping(value = "login", method = RequestMethod.POST)
	@ResponseBody
	public MallApiResponse loginSubmit(EnterpriseDto dto, HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {
		Integer logerrNum = (Integer) request.getSession().getAttribute("logerrNum");
		try {
			// 过滤不带验证码的请求
			checkCaptcha(dto, request);

			// session.setAttribute("strCode", strCode);
			String strCode = (String) session.getAttribute("strCode");
			if (dto != null && dto.getValidateCode() != null) {
				// 检查验证码是否正确
				if (!dto.getValidateCode().equals(strCode)) {
					throw new WebException(MallrApiResponseCode._1000122);
				}
			}
			// 验证用户密码是否正确
			Enterprise loginResult = enterpriseService.login(dto);
			 request.getSession().setAttribute("logerrNum",0);
			/**
			 * 如果登录成功，保存session信息
			 */
			EnterpriseAgent enterpriseAgent = new EnterpriseAgent();
			enterpriseAgent.setAccount(loginResult.getAccount());
			enterpriseAgent.setEnterpiseName(loginResult.getEnterpiseName());
			enterpriseAgent.setId(loginResult.getId());
			enterpriseAgent.setAbsoluteHeadPicUrl(loginResult.getAbsoluteHeadPicUrl());
			// 配送方式
			enterpriseAgent.setDistributionMode(loginResult.getDistributionMode());
			
			request.getSession().setAttribute(EnterpriseAgent.REQUEST_ATTR_NAME, enterpriseAgent);
			
			return MallApiResponse.create();

		} catch (WebException e2) {
			logger.error("loginSubmit异常", e2);
			return MallApiResponse.create(e2.getCode(), e2.getMessage());
		} catch (ServiceException e1) {
			logger.error("loginSubmit异常", e1);
			if (logerrNum == null) {
				logerrNum = 0;
			}
			logerrNum = logerrNum + 1;
			request.getSession().setAttribute("logerrNum", logerrNum);
			return MallApiResponse.create(e1.getCode(), e1.getMessage());
		} catch (Exception e) {
			logger.error("loginSubmit异常", e);
			return MallApiResponse.create(MallrApiResponseCode._1000002.getCode(), "系统繁忙");
		}
	}
}

